package com.xiaoli.controller.user;

import com.xiaoli.constant.JwtClaimsConstant;
import com.xiaoli.dto.UserDTO;
import com.xiaoli.entity.User;
import com.xiaoli.exception.UserNotFoundException;
import com.xiaoli.properties.JwtProperties;
import com.xiaoli.result.Result;
import com.xiaoli.dto.UserLoginDTO;
import com.xiaoli.service.UserService;
import com.xiaoli.utils.JwtUtil;
import com.xiaoli.vo.UserInfoVO;
import com.xiaoli.vo.UserLoginVO;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 用户登录
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JwtProperties jwtProperties;
    /**
     *登录
     * @param userLoginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> userLogin(@RequestBody UserLoginDTO userLoginDTO){
        log.info("用户登录: {}",userLoginDTO);
        User result = userService.getByUserName(userLoginDTO.getUserName());
        User user = userService.userLogin(userLoginDTO);

        HashMap<String,Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID,user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        UserLoginVO userLoginVO = UserLoginVO.builder().
                id(user.getId())
                .userName(user.getUserName())
                .stuName(user.getStuName())
                .token(token)
                .build();
        //登录成功后生成jwt令牌校验
        return Result.success(userLoginVO);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public Result<String> logout() {
        return Result.success();
    }


    /**
     * 用户注册
     * @param user
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        log.info("用户注册：{}",user);
        userService.register(user);
        return Result.success();
    }

    /**
     * 用户信息显示，使用token检测id判断用户信息
     * @param token
     * @return
     */
    @PostMapping("/getInfo")
    public Result<UserInfoVO> getInfo(@RequestHeader("Authorization") String token){
        Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(),token);
        int userId = Integer.parseInt(claims.get(JwtClaimsConstant.USER_ID).toString());

        UserInfoVO userInfoVO = userService.getById(userId);
        return Result.success(userInfoVO);
    }
    /**
     * 用户信息更新操作
     * @param userDTO
     * @return
     */
    @PutMapping("/update")
    public Result userUpdate(@RequestBody UserDTO userDTO){
        return null;
    }


}
